<template>
  <div class="area-list">
    <!-- <header class="header">{{ regionStore.regionName }}</header> -->
    <div class="position-tree-spin" v-if="regionStore.loading">
      <span tip="加载中.."></span>
    </div>
    <div class="tree-container">
      <el-tree
        v-if="regionStore.regionTreeData.length"
        class="flex-1 overflow-auto"
        :tree-data="regionStore.regionTreeData"
        :defaultExpandAll="true"
        @select="onSelect"
        :selectedKeys="selectedKeys"
        blockNode
        :field-names="fieldNames"
      >
        <template #title="{ dataRef }">
          <div class="tree-select truncate flex justify-between" :title="dataRef.name">
            <div>{{ dataRef.name }}</div>
          </div>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref } from 'vue';
  import constantStore from '@/store/modules/constant';

  //当前选中的地区信息——默认选中第一个节点
  const selectedKeys = ref<any>([]);
  //自定义tree组件展示字段
  const fieldNames = {
    children: 'children',
    title: 'name',
    key: 'weight',
  };
  const emit = defineEmits(['area-change']);
  //树状结构数据
  const regionStore = constantStore();
  if (regionStore.regionTreeData.length) {
    const defaultArea = regionStore.regionTreeData[0] || {};
    emit('area-change', defaultArea.weight, defaultArea.name);
    selectedKeys.value = [defaultArea.weight];
  }
  const onSelect = (_select, info) => {
    selectedKeys.value = [info.node.weight];
    emit('area-change', info.node.weight, info.node.name);
  };

  const resetTreeSelect = () => {
    selectedKeys.value = [];
  };

  defineExpose({
    resetTreeSelect,
  });

  watch(
    () => regionStore.regionTreeData,
    (v) => {
      //处理数组
      const defaultArea = v[0] || {};
      emit('area-change', defaultArea.weight, defaultArea.name);
      selectedKeys.value = [defaultArea.weight];
    },
    { deep: true },
  );
</script>
<style scoped lang="scss">
  .area-list {
    position: relative;
    height: 100%;
    .header {
      margin: 0 0 16px 20px;
      font-size: 16px;
    }
    .tree-container {
      height: calc(100% - 38px);
      overflow: auto;
    }
    .position-tree-spin {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    :deep(.el-tree-switcher) {
      align-self: center !important;
    }
    :deep(.el-tree-treenode-selected) {
      color: #1677ff;
      background: #e3edfb;
    }
    :deep(.el-tree-node-selected) {
      background: #e3edfb;
    }
    :deep(.el-tree-node-content-wrapper:hover) {
      background-color: rgba(0, 0, 0, 0);
    }
    .tree-select {
      height: 40px;
      line-height: 40px;
    }
  }
</style>
